/*
 * @lc app=leetcode.cn id=859 lang=java
 *
 * [859] 亲密字符串
 */

// @lc code=start
class Solution {
    public boolean buddyStrings(String s, String goal) {
        //至少两个字符串长度是相等的
        if(s.length() != goal.length())return false;
        //完全相等时，得有两个字符是重复的
        if(s.equals(goal)){
            int[] count = new int[26];
            for(int i=0; i<goal.length(); i++){
                count[s.charAt(i)-'a'] ++;
                if(count[s.charAt(i)-'a'] > 1){
                    return true;
                }
            }
            return false;
        }
        //不完全相等时
        else{
            //只有两处字符不同
            int diffCount = 0;
            //且能两处不同和字符，能交叉相等
            int diff1=-1, diff2=-1;

            int index=0;
            while(index < s.length() && diffCount <= 2){
                if(s.charAt(index) != goal.charAt(index)){
                    diffCount++;
                    if(diff1==-1){
                        diff1 = index;
                    }else{
                        diff2 = index;
                    }
                }
                index++;
            }
            System.out.println("diffCount:"+diffCount+",diff1:"+diff1+",diff2:"+diff2);
            //只有两处字符不同
            if(diffCount!=2){
                return false;
            }
            //且能两处不同和字符，能交叉相等
            if(s.charAt(diff1) == goal.charAt(diff2) && s.charAt(diff2) == goal.charAt(diff1)){
                return true;
            }else{
                return false;
            }
        }
    }
}
// @lc code=end

